package com.cicigodd.brick.plug.security.Interceptor;

import com.cicigodd.brick.plug.cache.api.RedisCacheServiceApi;
import com.cicigodd.brick.plug.common.entity.LoginUser;
import com.cicigodd.brick.plug.common.exception.AuthException;
import com.cicigodd.brick.plug.common.utils.AuthUtil;
import com.cicigodd.brick.plug.jwt.api.JwtServiceContext;
import com.cicigodd.brick.plug.security.Interceptor.base.BaseSecurityInterceptor;
import com.cicigodd.brick.plug.security.api.ResourceCollectorApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 鉴权的过滤器，用来鉴权token
 *
 * @author cicigodd
 * @date 2022/09/23 08:42:00
 */
@Component
@Slf4j
public class AuthJwtTokenSecurityInterceptor extends BaseSecurityInterceptor {

    @Resource
    private RedisCacheServiceApi<LoginUser> loginUserCache;
    @Resource
    private ResourceCollectorApi resourceCollectorApi;

    @Override
    public void filterAction(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        // 1. 获取当前请求的路径
        String requestURI = httpServletRequest.getRequestURI();
        // 2.判断此接口是否需要过滤
        Boolean booleam = resourceCollectorApi.checkPermission(requestURI);
        if (booleam) {
            // 3.获取token如果获取不到会抛出异常
            String token = AuthUtil.getToken();
            // 4. 校验jwt token本身是否有问题
            JwtServiceContext.me().validateTokenWithException(token);
            // 5. 校验session里是否有token
            LoginUser loginUser = loginUserCache.get(token);
            if (loginUser == null) {
                throw new AuthException("当前登录会话过期，请重新登录");
            }
        }
    }
}
